﻿var logoItemHtml = '' + '<div class="col-xs-3">'
		+ '	<img class = "logoItem" src="{src}" />' + '</div>';

$(function () {
    loadSource();
    bindLogoUpload();

    $("#subBtn").on("click", submit);
});

function initIfm() {
    var wh = $(window).height(); // 当前网页课件区域高度
    var iframeTop = $(".iframe-body iframe").offset().top; // 框架距顶部的距离
    $(".iframe-body iframe").css("height", wh - iframeTop + "px"); // 把iframe全屏显示
}

// 解析源代码
function loadSource() {
    var url = getQueryString("url");
    if (url == null || url.length == 0) {
        Alert("没用可用的网址");
        return;
    }

    if (url.indexOf("http://mp.weixin.qq.com") == 0) {
        // 微信订阅号文章、今日头条 单独处理
        loadWxUrl(url);
    } else if (url.indexOf("toutiao.com") != -1) {
        loadTouTiao(url);
    } else {
        $(".iframe-body").append("<iframe src = '" + url + "'></iframe>");
        initIfm();
        loadInfo(url);
    }
}

/**
* 获取网络标题图片等信息
* 
* @param url
*/
function loadInfo(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetEditInfo", {
        url: url
    },
        fillData, "json");
}


/**
* @param data
*            处理返回的数据
*/
function fillData(data) {
    wait.dismiss();
    if (data.code != 0) {
        wait.show(data.msg);
        return;
    }
    $("#title").val(data.item.title);

    // 默认第一张图片为头图
    if (data.item.imgList.length > 0) {
        $(".logo").attr("src", data.item.imgList[0]);
    }
    $(data.item.imgList).each(function () {
        $("#imgList").append(logoItemHtml.replace(/{src}/, this));
    });

    // 候选图片点击事件
    $(".logoItem").off("click");
    $(".logoItem").on("click", function () {
        $(".logo").attr("src", $(this).attr("src"));
    });
}

// 绑定logo图片上传
function bindLogoUpload() {

    // 标题logo
    $("#logoFile")
			.fileinput(
					{
					    showUpload: false,
					    showCaption: false,
					    showPreview: false,
					    browseLabel: '',
					    browseClass: "",
					    removeClass: "hide",
					    browseIcon: '<button id = "btnUploadLogo" class="btn btn-default btn-block Upcolor">上传logo</button>',
					    fileType: "any",
					    allowedFileExtensions: ['jpg', 'png', 'gif', 'bmp',
								'jpeg']
					});

    var userAgent = navigator.userAgent.toLocaleLowerCase();
    if (userAgent.indexOf("wjx") != -1 && userAgent.indexOf("android") != -1) {

        //客户端
        $("#logoFile").hide();

        $("#btnUploadLogo").on("click", function () {
            var param = { cutType: 1, width: 300, height: 300, callback: "resetLogo", url: "http://" + window.location.host + "/Client/Ajax/Upload.ashx?Img" };
            var p = JSON.stringify(param);
            window.location.href = "callback://imageUpload?" + p;
            return false;
        });
    }
    else {
        // 选择了图片提交图片
        $("#logoFile").change(function () {
            if ($(this).val().length == 0) {
                toast.show("文件格式错误");
                return;
            }
            wait.show();

            //选择好文件后提交表单
            $("#logoUpload").ajaxSubmit({
                type: 'post',
                dataType: "json",
                url: '/Client/Ajax/Upload.ashx?Img&is_cut=1&width=300&height=300',
                success: function (data) {
                    wait.dismiss();
                    if (data.code == 0) {
                        resetLogo(data.item);
                    }
                    else {
                        toast.show(data.msg);
                    }
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    wait.dismiss();
                    $(".logo").val("");
                    toast.show("图片文件太大或文件格式不正确");
                }
            });
        });
    }
}

function resetLogo(src) {

    $(".logo").attr("src", src);
    $("#imgList").append(logoItemHtml.replace(/{src}/, src));

    // 候选图片点击事件
    $(".logoItem").off("click");
    $(".logoItem").on("click", function () {
        $(".logo").attr("src", $(this).attr("src"));
    });
}

/**
* 绑定提交事件
*/
function submit() {
    var title = $("#title").val();
    if (title.length == 0) {
        toast.show("标题不能为空");
        return;
    }
    var logo = $(".logo").attr("src");
    if (logo == "img/default.png") {
        toast.show("请设置一张分享logo");
        return;
    }
    var url = getQueryString("url");

    var ec = encodeURIComponent;

    var param = "&url_title=" + ec(title) + "&url_logo=" + ec(logo) + "&url=" + ec(url);
    AjaxStart("ajax/fc_article.ashx?add", param, function (data) {
        if (data.code == 0) {
            Alert("添加成功，请完善设置");
            setTimeout(function () { window.location.href = 'makeset.html?id=' + data.item }, 1000);
        }
        else
            Alert(data.msg);
    });

    //window.location.href = "to_detail.aspx?type=2&title=" + ec(title) + "&logo=" + ec(logo) + "&url=" + ec(url);
}




//微信订阅号文章 单独处理
function loadWxUrl(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            loadInfo(url);

            window.ifm = data.item;
            $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'javascript:parent.ifm'></iframe>");
            initIfm();
            ifmLoad();
        }
        else {
            toast.show(data.msg);
        }

    }, "json");
}



function ifmLoad() {
    setTimeout(function () {

        //解决ios微信链接内容显示不全Bug
        if ($("#ifmUrl").attr("src").indexOf("http") != 0 && navigator.userAgent.toLowerCase().indexOf("iphone os") != -1) {
            $("#ifmUrl").contents().find("body").css("width", $(window).width() + "px");
        }

        $("#ifmUrl").contents().find("[data-src]").each(function () {
            $(this).attr("src", $(this).attr("data-src"));
        });

        reloadWxVideo();
    }, 500);
}


//处理微信视频
function reloadWxVideo() {
    var iframeDoc = $("#ifmUrl").contents();

    var videoFrame = $(iframeDoc).find("iframe");

    //判断是否视频
    if (videoFrame.length > 0) {

        $(videoFrame).each(function () {


            var videoUrl = $(this).attr("src");
            $($(this)).removeAttr("src");

            //提取视频id
            var vid = videoUrl.substring(videoUrl.indexOf("vid="))
            vid = vid.substring(4, vid.indexOf("&"));

            //视频页面 不含参数
            var videoHost = videoUrl.substring(0, videoUrl.indexOf("?")).replace("preview", "player");

            //修改后的视频宽度
            var vw = $(window).width() - 30;

            //修改后的视频高度
            var vh = vw / 500 * 375

            //设置兼容微信视频
            videoUrl = videoHost + "?vid=" + vid + "&width=" + vw + "&height=" + vh + "&auto=0"
            $(this).attr("src", videoUrl);

            //解决超出的空白
            $(this).css("width", vw + "px");

            //解决超高空白
            $(this).css("height", vh + "px");

            $(this).attr("width", vw);
            $(this).attr("height", vh);
        });
    }
}

//头条文章 单独处理
function loadTouTiao(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            loadInfo(url);
            $(".iframe-body").append("<iframe id = 'ifmUrl' src = '" + url + "'></iframe>");
            initIfm();
        }
        else {
            toast.show(data.msg);
        }

    }, "json");
}